package cn.iocoder.yudao.module.data.third;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author pokbrin
 * @date 2023-07-06 10:57
 */
public interface IBaseRequest<S extends IBaseResponse> {

    String name();

    String host();

    String url();

    default Map<String, String> headers() {
        return null;
    }

    Class<S> responseClass();

    Headers DEFAULT_HEAD = new Headers.Builder().build();


    default S doGet() {
        String clientName = this.name();
        Logger log = LoggerFactory.getLogger(this.getClass());
        Map<String, String> hMap = this.headers();
        Headers headers = this.DEFAULT_HEAD;
        if (CollUtil.isNotEmpty(hMap)) {
            Headers.Builder hb = new Headers.Builder();
            hMap.forEach(hb::add);
            headers = hb.build();
        }
        String url = this.url();
        if (log.isDebugEnabled()) {
            log.debug("{}-数据请求地址:{}", clientName, url);
        }
        Request request = new Request.Builder()
                .headers(headers)
                .url(url)
                .build();
        String respStr = null;
        try {
            OkHttpClient httpClient = SpringUtil.getBean(OkHttpClient.class);
            Response execute = httpClient.newCall(request).execute();
            respStr = execute.body().string();
        } catch (IOException e) {
            log.error("{}-执行异常:{}", clientName, e.getMessage());
        }
        if (log.isDebugEnabled()) {
            log.debug("{}-请求响应:{}", clientName, JsonUtils.toJsonPrettyString(respStr));
        }
        return JsonUtils.parseObject(respStr, this.responseClass());
    }

    default S doPost() throws Exception {
        //do nothing
        return null;
    }

}
